package com.ztgf.search.server.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Maps;
import com.ztgf.commodity.models.dto.BrandInfoDTO;
import com.ztgf.commodity.models.dto.CategoryBrandAttributesRelationDTO;
import com.ztgf.commodity.models.dto.CommodityCategoryDTO;
import com.ztgf.commodity.models.dto.CommodityInfoDTO;
import com.ztgf.commodity.models.service.IBrandInfoService;
import com.ztgf.commodity.models.service.ICategoryBrandAttributesRelationService;
import com.ztgf.commodity.models.service.ICommodityCategoryService;
import com.ztgf.commodity.models.service.ICommodityInfoService;
import com.ztgf.commodity.models.vo.CommodityEsVO;
import com.ztgf.common.constant.Result;
import com.ztgf.search.models.bean.BrandsBean;
import com.ztgf.search.models.bean.Constant;
import com.ztgf.search.models.bean.SearchRequestBean;
import com.ztgf.search.models.bean.SearchResponseBean;
import com.ztgf.search.models.dto.EsGoodsDTO;
import com.ztgf.search.models.dto.EsShopDTO;
import com.ztgf.search.models.service.IShopSearchService;
import com.ztgf.search.models.service.SearchService;
import com.ztgf.search.server.utils.CollectionHelp;
import com.ztgf.search.server.utils.StringHelper;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.ScoreSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;

import java.io.IOException;
import java.sql.Wrapper;
import java.util.*;

import static com.ztgf.common.utils.UtilConstants.isNull;

@Slf4j
@DubboService
public class SearchServiceImpl implements SearchService {

    @Qualifier("restHighLevelClient")
    @Autowired
    public RestHighLevelClient client;
    @Autowired
    private ElasticsearchServiceImpl elasticsearchService;
    @DubboReference
    private ICommodityInfoService commodityInfoService;
    @DubboReference
    private IBrandInfoService brandInfoService;
    @DubboReference
    private IShopInfoService shopInfoService;
    @DubboReference
    private IShopSearchService shopSearchService;
    @DubboReference
    private ICommodityCategoryService commodityCategoryService;
    @DubboReference
    private ICategoryBrandAttributesRelationService categoryBrandAttributesRelationService;

    private static final int batchImportSize = 40000;// 一个批次的最大数据量

    private static final String aliasename = "index_goods";

    private static final String typeName = "goods";

    private static final String shopTypeName = "shop";


//    @Override
//    public SearchResponseBean searchGoods(String aliasName, String type, String searchFields, SearchRequestBean sbean) {
//        /*if(sbean.getCategoryId() == null || sbean.getCategoryId().equals("")){
//            return new SearchResponseBean();
//        }*/
//
//        long t1 = System.currentTimeMillis();
//        Map<String, Float> fields = this.getFieldsMap(searchFields);
//        SearchResponseBean searchResponseBean = new SearchResponseBean();
//        SearchRequest searchRequest = new SearchRequest(aliasName);
//        searchRequest.types(type);
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        // 排序规则:0最新商品,1最高人气,2评论最多,3价格高到低,4价格低到高
//        if (null != sbean.getIsNew()) {
//            if (sbean.getIsNew() == 0) {
//                searchSourceBuilder.sort("createTime", SortOrder.DESC);
//            } else if (sbean.getIsNew() == 1) {
//                searchSourceBuilder.sort("popularity", SortOrder.DESC);
//            } else if (sbean.getIsNew() == 2) {
//                searchSourceBuilder.sort("evaluationNum", SortOrder.DESC);
//            } else if (sbean.getIsNew() == 3) {
//                searchSourceBuilder.sort("price", SortOrder.DESC);
//            } else if (sbean.getIsNew() == 4) {
//                searchSourceBuilder.sort("price", SortOrder.ASC);
//            } else {
//                searchSourceBuilder.sort("browseAmount", SortOrder.DESC);
//            }
//        } else {
//            searchSourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.DESC));
//        }
//
//
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        // 关键词
//        if (StringHelper.isNotEmpty(sbean.getGoodsKeyWord())) {
//            // 处理高亮字段
//            HighlightBuilder highlightBuilder = new HighlightBuilder();
//            highlightBuilder.field("goodsNameIkMaxWord");
//            highlightBuilder.field("goodsNameIkSmart");
//            highlightBuilder.requireFieldMatch(true);
//            // 前缀后缀
//            highlightBuilder.preTags("<span style='color:red'>");
//            highlightBuilder.postTags("</span>");
//            searchSourceBuilder.highlighter(highlightBuilder);
////            // 查询商品名称
////            MatchPhraseQueryBuilder matchPhraseQuery = QueryBuilders.matchPhraseQuery("goodsName", sbean.getGoodsKeyWord());
//            // 关键词查询
//            String[] split = sbean.getGoodsKeyWord().split(Constant.BLANKSTR);
//            for (String key : split) {
//                if (StringHelper.isNotEmpty(key)) {
//                    MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(StringHelper.removeBlank(key)).fields(fields);
//                    // 构建查询
//                    boolQuery.must(multiMatchQueryBuilder);
//                }
//            }
//        }
//
//        // 品牌名称
//        if (StringHelper.isNotEmpty(sbean.getBrandNames())) {
//            String[] brandNames = sbean.getBrandNames().split(",");
//            boolQuery.must(QueryBuilders.termsQuery("brandName", brandNames));
//        }
//        BoolQueryBuilder should1 = null;
//        BoolQueryBuilder boolQueryBuilder11= QueryBuilders.boolQuery();
//        // 筛选属性名称
//        if (StringHelper.isNotEmpty(sbean.getFilterNames())) {
//            String[] filterNames = sbean.getFilterNames().split(",");
//            for (String name : filterNames) {
//                if (StringHelper.isNotEmpty(name)) {
//                   // TermsQueryBuilder query = QueryBuilders.termsQuery("filterName", name);
//                    should1 = boolQueryBuilder11.should(QueryBuilders.matchPhraseQuery("filterName", name));
//                }
//            }
//            boolQuery.must(should1);
//        }
//        // 标签属性ids
//        if (StringHelper.isNotEmpty(sbean.getLabelIds())) {
//            String[] labelIds = sbean.getLabelIds().split(",");
//            for (String labelId : labelIds) {
//                if (StringHelper.isNotEmpty(labelId)) {
//                    TermsQueryBuilder query = QueryBuilders.termsQuery("labelIds", labelId);
//                    boolQuery.must(query);
//                }
//            }
//        }
//        // 类目id
//        BoolQueryBuilder should2 = null;
//        BoolQueryBuilder boolQueryBuilder22= QueryBuilders.boolQuery();
//        if (null != sbean.getCategoryId()) {
////            List<Long> list = new ArrayList<>();
////            list.add(sbean.getCategoryId());
////            EntityWrapper<CommodityCategoryDTO> wrapper  = new EntityWrapper<>();
////            wrapper.eq("parent_id",sbean.getCategoryId());
////            List<CommodityCategoryDTO> commodityCategoryDTOS = commodityCategoryService.selectList(wrapper);
////            if (commodityCategoryDTOS!=null && commodityCategoryDTOS.size()>0){
////                for (CommodityCategoryDTO commodityCategoryDTO : commodityCategoryDTOS) {
////                    list.add(commodityCategoryDTO.getId());
////                    EntityWrapper<CommodityCategoryDTO> wrapper1  = new EntityWrapper<>();
////                    wrapper1.eq("parent_id",commodityCategoryDTO.getId());
////                    List<CommodityCategoryDTO> commodityCategoryDTOS1 = commodityCategoryService.selectList(wrapper1);
////                    if (commodityCategoryDTOS1!=null && commodityCategoryDTOS1.size()>0){
////                        for (CommodityCategoryDTO categoryDTO : commodityCategoryDTOS1) {
////                            list.add(categoryDTO.getId());
////                            EntityWrapper<CommodityCategoryDTO> wrapper2  = new EntityWrapper<>();
////                            wrapper2.eq("parent_id",categoryDTO.getId());
////                            List<CommodityCategoryDTO> commodityCategoryDTOS2 = commodityCategoryService.selectList(wrapper2);
////                            if (commodityCategoryDTOS2!=null && commodityCategoryDTOS2.size()>0){
////                                for (CommodityCategoryDTO dto : commodityCategoryDTOS2) {
////                                    list.add(dto.getId());
////                                }
////                            }
////                        }
////                    }
////                }
////            }
//            QueryBuilder builder = QueryBuilders.multiMatchQuery(sbean.getCategoryId(),"categoryId","firstCategoryId","parentCategoryId");
////                        .should(QueryBuilders.matchPhraseQuery("parentCategoryId", aLong))
////                        .should(QueryBuilders.matchPhraseQuery("firstCategoryId", aLong));
//
//
//            boolQuery.must(builder);
//         /*   BoolQueryBuilder should = QueryBuilders.boolQuery().should(QueryBuilders.matchPhraseQuery("categoryId", sbean.getCategoryId()))
//                    .should(QueryBuilders.matchPhraseQuery("parentCategoryId", sbean.getCategoryId()))
//                    .should(QueryBuilders.matchPhraseQuery("firstCategoryId", sbean.getCategoryId()));
//            boolQuery.must(should);*/
//        }
//
//        long t2 = System.currentTimeMillis();
//        log.error("----------1--------"+(t2-t1));
//        // 店铺id
//        if (null != sbean.getSellerShopId()) {
//            boolQuery.must(QueryBuilders.matchPhraseQuery("sellerShopId", sbean.getSellerShopId()));
//        }
//        if(sbean.getCategoryId() == null && StringHelper.isEmpty(sbean.getGoodsKeyWord())) {
//            SearchSourceBuilder searchSourceBuilder1 = new SearchSourceBuilder();
//            searchSourceBuilder1.query(QueryBuilders.matchAllQuery());
//            searchSourceBuilder1.from(0);
//            searchSourceBuilder1.size(9999);
//            SearchRequest searchRequestGoods = new SearchRequest("index_goods_2020");
//            searchRequestGoods.source(searchSourceBuilder1);
//            searchRequestGoods.types("goods");
//            SearchResponse searchGoods = null;
//            try {
//                searchGoods = client.search(searchRequestGoods, RequestOptions.DEFAULT);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            SearchHit[] hits1 = searchGoods.getHits().getHits();
//            if (CollectionHelp.isArrayNotEmpty(hits1)) {
//                HashSet<Long> set = new HashSet<>();
//                for (SearchHit hit1 : hits1) {
//                    Map<String, Object> sourceAsMap1 = hit1.getSourceAsMap();
//                    EsGoodsDTO searchGoodsBean1 = JSONObject.parseObject(JSONObject.toJSONString(sourceAsMap1), EsGoodsDTO.class);
//                    searchGoodsBean1.setScore(hit1.getScore());
//                    BrandInfoDTO select = brandInfoService.selectById(searchGoodsBean1.getBrandId());
//                    if (select != null) {
//                        boolean add = set.add(select.getId());
//                        if (add) {
//                            BrandsBean brandsBean = new BrandsBean();
//                            brandsBean.setId(select.getId());
//                            brandsBean.setName(select.getName());
//                            searchResponseBean.getBrandList().add(brandsBean);
//                        }
//                    }
//                }
//            }
//
//        }
//
//        long t3 = System.currentTimeMillis();
//        log.error("----------2--------"+(t3-t2));
//
//        if(null != sbean.getCategoryId() && StringHelper.isEmpty(sbean.getGoodsKeyWord())){
//            // 处理品牌
//            EntityWrapper wrapper = new EntityWrapper();
//            wrapper.and("id in (SELECT ci.brand_id FROM commodity_info ci\n" +
//                    "JOIN shop_info si ON ci.shop_id = si.id \n" +
//                    "WHERE 1=1\n" +
//                    "AND si.merchant_type = 1\n" +
//                    "AND si.frozen_status = 0\n" +
//                    "AND si.admin_frozen_status = 0\n" +
//                    "AND ci.is_publish = 1\n" +
//                    "AND ci.status = 0\n" +
//                    "and ci.category_id in\n" +
//                    "(\n" +
//                    "SELECT id FROM commodity_category WHERE parent_id in \n" +
//                    "(SELECT id FROM commodity_category WHERE parent_id in \n" +
//                    "(SELECT id FROM commodity_category WHERE parent_id = {0}))\n" +
//                    "UNION\n" +
//                    "SELECT id FROM commodity_category WHERE parent_id in \n" +
//                    "(SELECT id FROM commodity_category WHERE parent_id = {1})\n" +
//                    "UNION \n" +
//                    "SELECT id FROM commodity_category WHERE parent_id = {2}\n" +
//                    ")\n" +
//                    "GROUP BY ci.brand_id\n" +
//                    ")", sbean.getCategoryId(), sbean.getCategoryId(), sbean.getCategoryId());
//            List<BrandInfoDTO> brandList = brandInfoService.selectList(wrapper);
//            if(CollectionUtils.isNotEmpty(brandList)){
//                for (BrandInfoDTO brandDTO : brandList){
//                    BrandsBean brandsBean = new BrandsBean();
//                    brandsBean.setId(brandDTO.getId());
//                    brandsBean.setName(brandDTO.getName());
//                    searchResponseBean.getBrandList().add(brandsBean);
//                }
//            }
////            List<Long> list = new ArrayList<>();
////            list.add(sbean.getCategoryId());
////            EntityWrapper<CommodityCategoryDTO> wrapper0  = new EntityWrapper<>();
////            wrapper0.eq("parent_id",sbean.getCategoryId());
////            List<CommodityCategoryDTO> commodityCategoryDTOS = commodityCategoryService.selectList(wrapper0);
////            if (commodityCategoryDTOS!=null && commodityCategoryDTOS.size()>0){
////                for (CommodityCategoryDTO commodityCategoryDTO : commodityCategoryDTOS) {
////                    list.add(commodityCategoryDTO.getId());
////                    EntityWrapper<CommodityCategoryDTO> wrapper1  = new EntityWrapper<>();
////                    wrapper1.eq("parent_id",commodityCategoryDTO.getId());
////                    List<CommodityCategoryDTO> commodityCategoryDTOS1 = commodityCategoryService.selectList(wrapper1);
////                    if (commodityCategoryDTOS1!=null && commodityCategoryDTOS1.size()>0){
////                        for (CommodityCategoryDTO categoryDTO : commodityCategoryDTOS1) {
////                            list.add(categoryDTO.getId());
////                            EntityWrapper<CommodityCategoryDTO> wrapper2  = new EntityWrapper<>();
////                            wrapper2.eq("parent_id",categoryDTO.getId());
////                            List<CommodityCategoryDTO> commodityCategoryDTOS2 = commodityCategoryService.selectList(wrapper2);
////                            if (commodityCategoryDTOS2!=null && commodityCategoryDTOS2.size()>0){
////                                for (CommodityCategoryDTO dto : commodityCategoryDTOS2) {
////                                    list.add(dto.getId());
////                                }
////                            }
////                        }
////                    }
////                }
////            }
////            long t4 = System.currentTimeMillis();
////            log.error("----------3--------"+(t4-t3));
////            if (list!=null && list.size()>0){
////                for (Long aLong : list) {
////                    EntityWrapper<CategoryBrandAttributesRelationDTO> categoryBrandAttributesRelationDTOEntityWrapper = new EntityWrapper<>();
////                    categoryBrandAttributesRelationDTOEntityWrapper.setSqlSelect("brand_id");
////                    categoryBrandAttributesRelationDTOEntityWrapper.eq("category_id",aLong);
////                    categoryBrandAttributesRelationDTOEntityWrapper.groupBy("brand_id");
////                    List<CategoryBrandAttributesRelationDTO> relationDTOList = categoryBrandAttributesRelationService.selectList(categoryBrandAttributesRelationDTOEntityWrapper);
////                    log.error("----relationDTOList----" + JSON.toJSONString(relationDTOList));
////                    if (relationDTOList !=null && relationDTOList.size()>0){
////                        for (CategoryBrandAttributesRelationDTO categoryBrandAttributesRelationDTO : relationDTOList) {
////                            BrandInfoDTO select = brandInfoService.selectById(categoryBrandAttributesRelationDTO.getBrandId());
////                            if (select != null) {
////                                EntityWrapper<CommodityInfoDTO> wrapper = new EntityWrapper<>();
////                                wrapper.setSqlSelect("shop_id");
////                                wrapper.eq("brand_id",select.getId());
////                                wrapper.eq("category_id",aLong);
////                                wrapper.eq("is_publish",1);
////                                wrapper.eq("status",0);
////                                wrapper.eq("audit_status",1);
////                                wrapper.eq("is_platform_shelf",0);
////                                wrapper.eq("is_remove",0);
////                                wrapper.eq("is_platform_remove",0);
////                                wrapper.groupBy("shop_id");
////                                List<CommodityInfoDTO> commodityInfoDTOS = commodityInfoService.selectList(wrapper);
////                                log.error("----commodityInfoDTOS----" + JSON.toJSONString(commodityInfoDTOS));
////                                if (commodityInfoDTOS!=null && commodityInfoDTOS.size()>0){
////                                    List<CommodityInfoDTO> objects = new ArrayList<>();
////                                    for (CommodityInfoDTO commodityInfoDTO : commodityInfoDTOS) {
////                                        boolean b = shopInfoService.checkShopIsClose(commodityInfoDTO.getShopId());
////                                        if (b){
////                                            objects.add(commodityInfoDTO);
////                                            break;
////                                        }
////                                    }
////                                    if (objects!=null && objects.size()>0){
////                                        BrandsBean brandsBean = new BrandsBean();
////                                        brandsBean.setId(select.getId());
////                                        brandsBean.setName(select.getName());
////                                        searchResponseBean.getBrandList().add(brandsBean);
////                                    }
////                                }
////                            }
////                        }
////                        /*if (searchResponseBean.getBrandList()==null ||  searchResponseBean.getBrandList().size()==0){
////                            return new SearchResponseBean();
////                        }*/
////                    }/*else {
////                        return new SearchResponseBean();
////                    }*/
////                }
////                if (searchResponseBean.getBrandList()==null ||  searchResponseBean.getBrandList().size()==0){
////                    return new SearchResponseBean();
////                }else {
////                    LinkedHashSet<BrandsBean> hashSet = new LinkedHashSet<>(searchResponseBean.getBrandList());
////                    searchResponseBean.setBrandList(new ArrayList<>(hashSet));
////                }
////            }
//
//            long t5 = System.currentTimeMillis();
//            log.error("----------4--------"+(t5-t3));
//        }
//
//        long t6 = System.currentTimeMillis();
//
//        if(StringHelper.isNotEmpty(sbean.getGoodsKeyWord())){
//            searchSourceBuilder.from(0);
//            searchSourceBuilder.size(9999);
//            searchSourceBuilder.query(boolQuery);
//            SearchRequest searchRequestGoods = new SearchRequest("index_goods_2020");
//            searchRequestGoods.source(searchSourceBuilder);
//            searchRequestGoods.types("goods");
//            SearchResponse searchGoods = null;
//            try {
//                searchGoods = client.search(searchRequestGoods, RequestOptions.DEFAULT);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            SearchHit[] hits1 = searchGoods.getHits().getHits();
//            if (CollectionHelp.isArrayNotEmpty(hits1)) {
//                HashSet<Long> set = new HashSet<>();
//                for (SearchHit hit1 : hits1) {
//                    Map<String, Object> sourceAsMap1 = hit1.getSourceAsMap();
//                    EsGoodsDTO searchGoodsBean1 = JSONObject.parseObject(JSONObject.toJSONString(sourceAsMap1), EsGoodsDTO.class);
//                    if (searchGoodsBean1.getBrandId()!=null){
//                        boolean add = set.add(Long.valueOf(searchGoodsBean1.getBrandId()));
//                        if (add) {
//                            BrandsBean brandsBean = new BrandsBean();
//                            brandsBean.setId(Long.valueOf(searchGoodsBean1.getBrandId()));
//                            brandsBean.setName(searchGoodsBean1.getBrandName());
//                            searchResponseBean.getBrandList().add(brandsBean);
//                        }
//                    }
//                }
//            }
//        }
//
//        long t7 = System.currentTimeMillis();
//        log.error("----------5--------"+(t7-t6));
//        // 分页
//        if (sbean.getPageSize() != null && sbean.getPageNo() != null) {
//            searchSourceBuilder.from((sbean.getPageNo() - 1) * sbean.getPageSize());
//            searchSourceBuilder.size(sbean.getPageSize());
//        } else {
//            searchSourceBuilder.from(0);
//            searchSourceBuilder.size(50);
//        }
//        final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L));
//        ScoreSortBuilder sortBuilder = SortBuilders.scoreSort().order(SortOrder.DESC);
//        searchSourceBuilder.sorts().add(sortBuilder);
//        searchSourceBuilder.query(boolQuery);
//        searchRequest.source(searchSourceBuilder);
//        try {
//            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//            SearchHits hits = searchResponse.getHits();
//            SearchHit[] searchHits = hits.getHits();
//            if (CollectionHelp.isArrayNotEmpty(searchHits)) {
//                HashSet<Long> set = new HashSet<>();
//                    for (SearchHit hit : searchHits) {
//                        // 解析高亮字段
//                        // 获取高亮字段
//                        Map<String, HighlightField> highlightFieldMap = hit.getHighlightFields();
//                        // 原来的结果
//                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
//                        HighlightField goodsNameIkSmart = highlightFieldMap.get("goodsNameIkSmart");
//                        HighlightField goodsNameIkMaxWord = highlightFieldMap.get("goodsNameIkMaxWord");
//                        String highlightField = this.updateHighlightField(goodsNameIkSmart, goodsNameIkMaxWord);
//                        if (StringHelper.isNotEmpty(highlightField)) {
//                            sourceAsMap.put("goodsName", highlightField);
//                        }
//                        EsGoodsDTO searchGoodsBean = JSONObject.parseObject(JSONObject.toJSONString(sourceAsMap), EsGoodsDTO.class);
//                        searchGoodsBean.setScore(hit.getScore());
//                        searchResponseBean.getListGoodsBean().add(searchGoodsBean);
//                    }
//            }
//            CountRequest countRequest = new CountRequest(aliasName);
//            countRequest.types(type);
//            SearchSourceBuilder countSourceBuilder = new SearchSourceBuilder();
//            countSourceBuilder.query(boolQuery);
//            countRequest.source(countSourceBuilder);
//            CountResponse countResponse = client.count(countRequest, RequestOptions.DEFAULT);
//            searchResponseBean.setTotalNum(countResponse.getCount());
//            searchResponseBean.setPageNum(sbean.getPageNo().longValue());
//            searchResponseBean.setSize(sbean.getPageSize().longValue());
//            long t8 = System.currentTimeMillis();
//            log.error("----------7--------"+(t8-t7));
//        } catch (IOException e) {
//            log.error("搜索商品错误信息:{}", e);
//        }
//        return searchResponseBean;
//    }
//
//
//    public SearchResponseBean searchGoods2(String aliasName, String type, String searchFields, SearchRequestBean sbean) {
//        Map<String, Float> fields = this.getFieldsMap(searchFields);
//        SearchResponseBean searchResponseBean = new SearchResponseBean();
//        SearchRequest searchRequest = new SearchRequest(aliasName);
//        searchRequest.types(type);
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        // 排序规则:0最新商品,1最高人气,2评论最多,3价格高到低,4价格低到高
//        if (null != sbean.getIsNew()) {
//            if (sbean.getIsNew() == 0) {
//                searchSourceBuilder.sort("createTime", SortOrder.DESC);
//            } else if (sbean.getIsNew() == 1) {
//                searchSourceBuilder.sort("popularity", SortOrder.DESC);
//            } else if (sbean.getIsNew() == 2) {
//                searchSourceBuilder.sort("evaluationNum", SortOrder.DESC);
//            } else if (sbean.getIsNew() == 3) {
//                searchSourceBuilder.sort("price", SortOrder.DESC);
//            } else if (sbean.getIsNew() == 4) {
//                searchSourceBuilder.sort("price", SortOrder.ASC);
//            } else {
//                searchSourceBuilder.sort("browseAmount", SortOrder.DESC);
//            }
//        } else {
//            searchSourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.DESC));
//        }
//
//
//        // 分页
//        searchSourceBuilder.size(1000);
//        final Scroll scroll = new Scroll(TimeValue.timeValueMinutes(1L));
//        ScoreSortBuilder sortBuilder = SortBuilders.scoreSort().order(SortOrder.DESC);
//        searchSourceBuilder.sorts().add(sortBuilder);
//        searchRequest.source(searchSourceBuilder);
//        searchRequest.scroll(scroll);
//        try {
//            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
//            String scrollId = searchResponse.getScrollId();
//            SearchHits hits = searchResponse.getHits();
//            SearchHit[] searchHits = hits.getHits();
//            if (CollectionHelp.isArrayNotEmpty(searchHits)) {
//                HashSet<Long> set = new HashSet<>();
//                while (searchHits != null && searchHits.length > 0) {
//                    for (SearchHit hit : searchHits) {
//                        //获取需要数据
//                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
//                        EsGoodsDTO searchGoodsBean = JSONObject.parseObject(JSONObject.toJSONString(sourceAsMap), EsGoodsDTO.class);
//                        searchGoodsBean.setScore(hit.getScore());
//
//                        BrandInfoDTO select = brandInfoService.selectById(searchGoodsBean.getBrandId());
//                        if (select != null) {
//                            boolean add = set.add(select.getId());
//                            if (add) {
//                                BrandsBean brandsBean = new BrandsBean();
//                                brandsBean.setId(select.getId());
//                                brandsBean.setName(select.getName());
//                                searchResponseBean.getBrandList().add(brandsBean);
//                            }
//                        }
//                    }
//
//                    SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
//                    scrollRequest.scroll(scroll);
//                    searchResponse = client.scroll(scrollRequest, RequestOptions.DEFAULT);
//                    scrollId = searchResponse.getScrollId();
//                    searchHits = searchResponse.getHits().getHits();
//                 }
//
//                // 清除滚屏
//                if (scrollId != null) {
//                    ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
//                    clearScrollRequest.addScrollId(scrollId);
//                    ClearScrollResponse clearScrollResponse = client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
//                    boolean succeeded = clearScrollResponse.isSucceeded();
//                }
//            }
//
//        } catch (IOException e) {
//            log.error("搜索商品错误信息:{}", e);
//        }
//        return searchResponseBean;
//    }

    @Override
    public SearchResponseBean searchGoods(String aliasName, String type, String searchFields, SearchRequestBean sbean) {
        Map<String, Float> fields = this.getFieldsMap(searchFields);
        SearchResponseBean searchResponseBean = new SearchResponseBean();
        SearchRequest searchRequest = new SearchRequest(aliasName);
        searchRequest.types(type);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 排序规则:0最新商品,1最高人气,2评论最多,3价格高到低,4价格低到高
        if (null != sbean.getIsNew()) {
            if (sbean.getIsNew() == 0) {
                searchSourceBuilder.sort("createTime", SortOrder.DESC);
            } else if (sbean.getIsNew() == 1) {
                searchSourceBuilder.sort("popularity", SortOrder.DESC);
            } else if (sbean.getIsNew() == 2) {
                searchSourceBuilder.sort("evaluationNum", SortOrder.DESC);
            } else if (sbean.getIsNew() == 3) {
                searchSourceBuilder.sort("price", SortOrder.DESC);
            } else if (sbean.getIsNew() == 4) {
                searchSourceBuilder.sort("price", SortOrder.ASC);
            } else {
                searchSourceBuilder.sort("browseAmount", SortOrder.DESC);
            }
        } else {
            searchSourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.DESC));
        }

        // 分页
        if (sbean.getPageSize() != null && sbean.getPageNo() != null) {
            searchSourceBuilder.from((sbean.getPageNo() - 1) * sbean.getPageSize());
            searchSourceBuilder.size(sbean.getPageSize());
        } else {
            searchSourceBuilder.from(0);
            searchSourceBuilder.size(10);
        }
        ScoreSortBuilder sortBuilder = SortBuilders.scoreSort().order(SortOrder.DESC);
        searchSourceBuilder.sorts().add(sortBuilder);
        searchRequest.source(searchSourceBuilder);


        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键词
        if (StringHelper.isNotEmpty(sbean.getGoodsKeyWord())) {
            // 处理高亮字段
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("goodsNameIkMaxWord");
            highlightBuilder.field("goodsNameIkSmart");
            highlightBuilder.requireFieldMatch(true);
            // 前缀后缀
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");
            searchSourceBuilder.highlighter(highlightBuilder);
            // 关键词查询
            String[] split = sbean.getGoodsKeyWord().split(Constant.BLANKSTR);
            for (String key : split) {
                if (StringHelper.isNotEmpty(key)) {
                    MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(StringHelper.removeBlank(key)).fields(fields);
                    // 构建查询
                    boolQuery.must(multiMatchQueryBuilder);
                }
            }
        }

        // 品牌名称
        if (StringHelper.isNotEmpty(sbean.getBrandNames())) {
            log.info("品牌搜索条件---------------------"+sbean.getBrandNames());
            String[] brandNames = sbean.getBrandNames().split(",");
            boolQuery.must(QueryBuilders.termsQuery("brandName", brandNames));
        }
        BoolQueryBuilder should1 = null;
        BoolQueryBuilder boolQueryBuilder11= QueryBuilders.boolQuery();
        // 筛选属性名称
        if (StringHelper.isNotEmpty(sbean.getFilterNames())) {
            String[] filterNames = sbean.getFilterNames().split(",");
            for (String name : filterNames) {
                if (StringHelper.isNotEmpty(name)) {
                    should1 = boolQueryBuilder11.should(QueryBuilders.matchPhraseQuery("filterName", name));
                }
            }
            boolQuery.must(should1);
        }
        // 标签属性ids
        if (StringHelper.isNotEmpty(sbean.getLabelIds())) {
            String[] labelIds = sbean.getLabelIds().split(",");
            for (String labelId : labelIds) {
                if (StringHelper.isNotEmpty(labelId)) {
                    TermsQueryBuilder query = QueryBuilders.termsQuery("labelIds", labelId);
                    boolQuery.must(query);
                }
            }
        }
        // 类目id
        if (null != sbean.getCategoryId()) {
            QueryBuilder builder = QueryBuilders.multiMatchQuery(sbean.getCategoryId(),"categoryId","firstCategoryId","parentCategoryId");
            boolQuery.must(builder);
        }

        // 店铺id
        if (null != sbean.getSellerShopId()) {
            boolQuery.must(QueryBuilders.matchPhraseQuery("sellerShopId", sbean.getSellerShopId()));
        }



        try {
            if(null == sbean.getCategoryId() && StringHelper.isEmpty(sbean.getGoodsKeyWord())) {
                log.info("boolQuery---------------2------------------"+boolQuery.toString());
                searchSourceBuilder.query(boolQuery);
                searchRequest.source(searchSourceBuilder);
                SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
                SearchHits hits = searchResponse.getHits();
                SearchHit[] searchHits = hits.getHits();
                if (CollectionHelp.isArrayNotEmpty(searchHits)) {
                    HashSet<Long> set = new HashSet<>();
                    for (SearchHit hit : searchHits) {
                        // 解析高亮字段
                        // 获取高亮字段
                        Map<String, HighlightField> highlightFieldMap = hit.getHighlightFields();
                        // 原来的结果
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();

                        log.info("sourceAsMap---------------------------------"+sourceAsMap.toString());

                        HighlightField goodsNameIkSmart = highlightFieldMap.get("goodsNameIkSmart");
                        HighlightField goodsNameIkMaxWord = highlightFieldMap.get("goodsNameIkMaxWord");
                        String highlightField = this.updateHighlightField(goodsNameIkSmart, goodsNameIkMaxWord);
                        if (StringHelper.isNotEmpty(highlightField)) {
                            sourceAsMap.put("goodsName", highlightField);
                        }
                        EsGoodsDTO searchGoodsBean = JSONObject.parseObject(JSONObject.toJSONString(sourceAsMap), EsGoodsDTO.class);
                        searchGoodsBean.setScore(hit.getScore());
                        searchResponseBean.getListGoodsBean().add(searchGoodsBean);

                        BrandInfoDTO select = brandInfoService.selectById(searchGoodsBean.getBrandId());
                        if (select != null) {
                            boolean add = set.add(select.getId());
                            if (add) {
                                BrandsBean brandsBean = new BrandsBean();
                                brandsBean.setId(select.getId());
                                brandsBean.setName(select.getName());
                                searchResponseBean.getBrandList().add(brandsBean);
                            }
                        }
                    }
                }
            }else {
                if (null != sbean.getCategoryId() && StringHelper.isEmpty(sbean.getGoodsKeyWord())) {
                    // 处理品牌
                    EntityWrapper wrapper = new EntityWrapper();
                    wrapper.and("id in (SELECT ci.brand_id FROM commodity_info ci\n" +
                            "JOIN shop_info si ON ci.shop_id = si.id \n" +
                            "WHERE 1=1\n" +
                            "AND si.merchant_type = 1\n" +
                            "AND si.frozen_status = 0\n" +
                            "AND si.admin_frozen_status = 0\n" +
                            "AND ci.is_publish = 1\n" +
                            "AND ci.status = 0\n" +
                            "and ci.category_id in\n" +
                            "(\n" +
                            "SELECT id FROM commodity_category WHERE parent_id in \n" +
                            "(SELECT id FROM commodity_category WHERE parent_id in \n" +
                            "(SELECT id FROM commodity_category WHERE parent_id = {0}))\n" +
                            "UNION\n" +
                            "SELECT id FROM commodity_category WHERE parent_id in \n" +
                            "(SELECT id FROM commodity_category WHERE parent_id = {1})\n" +
                            "UNION \n" +
                            "SELECT id FROM commodity_category WHERE parent_id = {2}\n" +
                            ")\n" +
                            "GROUP BY ci.brand_id\n" +
                            ")", sbean.getCategoryId(), sbean.getCategoryId(), sbean.getCategoryId());
                    List<BrandInfoDTO> brandList = brandInfoService.selectList(wrapper);
                    if (CollectionUtils.isNotEmpty(brandList)) {
                        for (BrandInfoDTO brandDTO : brandList) {
                            BrandsBean brandsBean = new BrandsBean();
                            brandsBean.setId(brandDTO.getId());
                            brandsBean.setName(brandDTO.getName());
                            searchResponseBean.getBrandList().add(brandsBean);
                        }
                    }
                }


                if (StringHelper.isNotEmpty(sbean.getGoodsKeyWord())) {
                    searchSourceBuilder.query(boolQuery);
                    SearchRequest searchRequestGoods = new SearchRequest("index_goods_2020");
                    searchRequestGoods.source(searchSourceBuilder);
                    searchRequestGoods.types("goods");
                    SearchResponse searchGoods = null;
                    try {
                        searchGoods = client.search(searchRequestGoods, RequestOptions.DEFAULT);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    SearchHit[] hits1 = searchGoods.getHits().getHits();
                    if (CollectionHelp.isArrayNotEmpty(hits1)) {
                        HashSet<Long> set = new HashSet<>();
                        for (SearchHit hit1 : hits1) {
                            Map<String, Object> sourceAsMap1 = hit1.getSourceAsMap();
                            EsGoodsDTO searchGoodsBean1 = JSONObject.parseObject(JSONObject.toJSONString(sourceAsMap1), EsGoodsDTO.class);
                            if (searchGoodsBean1.getBrandId() != null) {
                                boolean add = set.add(Long.valueOf(searchGoodsBean1.getBrandId()));
                                if (add) {
                                    BrandsBean brandsBean = new BrandsBean();
                                    brandsBean.setId(Long.valueOf(searchGoodsBean1.getBrandId()));
                                    brandsBean.setName(searchGoodsBean1.getBrandName());
                                    searchResponseBean.getBrandList().add(brandsBean);
                                }
                            }
                        }
                    }
                }

                sortBuilder = SortBuilders.scoreSort().order(SortOrder.DESC);
                searchSourceBuilder.sorts().add(sortBuilder);
                searchSourceBuilder.query(boolQuery);
                searchRequest.source(searchSourceBuilder);
                log.info("boolQuery---------------------------------"+boolQuery.toString());
                SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
                SearchHits hits = searchResponse.getHits();
                SearchHit[] searchHits = hits.getHits();
                if (CollectionHelp.isArrayNotEmpty(searchHits)) {
                    HashSet<Long> set = new HashSet<>();
                    for (SearchHit hit : searchHits) {
                        // 解析高亮字段
                        // 获取高亮字段
                        Map<String, HighlightField> highlightFieldMap = hit.getHighlightFields();
                        // 原来的结果
                        Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                        HighlightField goodsNameIkSmart = highlightFieldMap.get("goodsNameIkSmart");
                        HighlightField goodsNameIkMaxWord = highlightFieldMap.get("goodsNameIkMaxWord");
                        String highlightField = this.updateHighlightField(goodsNameIkSmart, goodsNameIkMaxWord);
                        if (StringHelper.isNotEmpty(highlightField)) {
                            sourceAsMap.put("goodsName", highlightField);
                        }
                        EsGoodsDTO searchGoodsBean = JSONObject.parseObject(JSONObject.toJSONString(sourceAsMap), EsGoodsDTO.class);
                        searchGoodsBean.setScore(hit.getScore());
                        searchResponseBean.getListGoodsBean().add(searchGoodsBean);
                    }
                }
            }
            CountRequest countRequest = new CountRequest(aliasName);
            countRequest.types(type);
            SearchSourceBuilder countSourceBuilder = new SearchSourceBuilder();
            countSourceBuilder.query(boolQuery);
            countRequest.source(countSourceBuilder);
            CountResponse countResponse = client.count(countRequest, RequestOptions.DEFAULT);
            searchResponseBean.setTotalNum(countResponse.getCount());
            searchResponseBean.setPageNum(sbean.getPageNo().longValue());
            searchResponseBean.setSize(sbean.getPageSize().longValue());


        } catch (IOException e) {
            log.error("搜索商品错误信息:{}", e);
        }
        return searchResponseBean;
    }

    @Override
    public SearchResponseBean searchBrand(String aliasName, String type, String searchFields, SearchRequestBean sbean) {
        // 处理品牌
        EntityWrapper wrapper = new EntityWrapper();
        wrapper.eq("is_publish",1);
        wrapper.eq("status",0);
        List<BrandInfoDTO> brandList = brandInfoService.selectList(wrapper);

        Map<String, Float> fields = this.getFieldsMap(searchFields);

        SearchResponseBean searchResponseBean = new SearchResponseBean();
        // 品牌名称
        if (null != brandList && brandList.size() > 0){
            for(BrandInfoDTO brandInfoDTO : brandList){

                SearchRequest searchRequest = new SearchRequest(aliasName);
                searchRequest.types(type);
                SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

                // 分页
                searchSourceBuilder.size(1);

                BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
                boolQuery.must(QueryBuilders.termsQuery("brandId", brandInfoDTO.getId().toString()));
                searchSourceBuilder.query(boolQuery);
                searchRequest.source(searchSourceBuilder);
                try{
                    SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
                    SearchHits hits = searchResponse.getHits();
                    SearchHit[] searchHits = hits.getHits();

                    if (CollectionHelp.isArrayNotEmpty(searchHits)) {
                        for(SearchHit hit : searchHits ){
                            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                            if (CollectionHelp.isMapEmpty(sourceAsMap)) {
                                brandList.remove(brandInfoDTO);
                            }else{
                                BrandsBean brandsBean = new BrandsBean();
                                brandsBean.setId(Long.valueOf(brandInfoDTO.getId()));
                                brandsBean.setName(brandInfoDTO.getName());
                                searchResponseBean.getBrandList().add(brandsBean);
                            }
                        }
                    }


                }catch (Exception e){

                }

            }

        }
        return searchResponseBean;

    }


    @Override
    public Result add() {
        Result<Object> result = new Result<>();
        List<CommodityEsVO> list = commodityInfoService.queryAllESGoods(0L);
        if (isNull(list)) {
            result.setCode(100003);
            result.setMsg("查询商品为空!");
            return result;
        }
        List<EsGoodsDTO> goodsList = new ArrayList<>();
        for (CommodityEsVO vo : list) {
            EsGoodsDTO goodsDTO = new EsGoodsDTO();
            goodsDTO.setId(vo.getId());
            goodsDTO.setLogUrl(vo.getLogUrl());
            goodsDTO.setGoodsName(vo.getGoodsName());
            goodsDTO.setGoodsNameIkSmart(vo.getGoodsName());
            goodsDTO.setGoodsNameIkMaxWord(vo.getGoodsName());
            goodsDTO.setDescription(vo.getDescription());
            goodsDTO.setPrice(vo.getPrice().doubleValue());
            goodsDTO.setOriginalPrice(vo.getOriginalPrice().doubleValue());
            goodsDTO.setPayUserNum(vo.getPayUserNum());
            goodsDTO.setSellerShopId(vo.getSellerShopId());
            goodsDTO.setSellerShopName(vo.getSellerShopName());
            goodsDTO.setSellerShopAddress(vo.getSellerShopAddress());
            goodsDTO.setBrandId(vo.getBrandId().toString());
            goodsDTO.setBrandName(vo.getBrandName());
            goodsDTO.setBrandNameIkSmart(vo.getBrandName());
            goodsDTO.setBrandNameIkMaxWord(vo.getBrandName());
            goodsDTO.setCategoryId(vo.getCategoryId());
            goodsDTO.setCategoryName(vo.getCategoryName());
            goodsDTO.setIsNew(vo.getIsNew());
            goodsDTO.setPopularity(vo.getPopularity());
            goodsDTO.setEvaluationNum(vo.getEvaluationNum());
            goodsDTO.setCreateTime(vo.getCreateTime());
            goodsDTO.setParentCategoryId(vo.getParentCategoryId());
            goodsDTO.setFirstCategoryId(vo.getFirstCategoryId());
            goodsDTO.setFilterIds(vo.getFilterIds());
            goodsDTO.setFilterNames(vo.getFilterNames());
            if (StringHelper.isNotEmpty(vo.getFilterNames())) {
                String[] split = vo.getFilterNames().split(",");
                goodsDTO.setFilterName(split);
            }
            if (StringHelper.isNotEmpty(vo.getLabelIds())) {
                String[] split = vo.getLabelIds().split(",");
                goodsDTO.setLabelIds(split);
            }
            goodsDTO.setIsXun(vo.getIsXun());
            goodsDTO.setBrowseAmount(vo.getBrowseAmount());
            goodsList.add(goodsDTO);
        }
        try {
            this.batchPost(goodsList.size(), 0, goodsList);
        } catch (IOException e) {
            log.info("添加商品到es失败!");
            e.printStackTrace();
        }
        result.setCode(0);
        result.setMsg("添加成功!");
        return result;
    }

    @Async
    @Override
    public void addGoods(String aliasName, String typeName, int begin, int end, List<EsGoodsDTO> totalList) {
        if (isNull(totalList)) {
            return;
        }
        List<EsGoodsDTO> postList = totalList.subList(begin, end);
        BulkRequest bulkRequest = new BulkRequest();
        for (EsGoodsDTO d : postList) {
            String jsonString = JSON.toJSONString(d);
            IndexRequest indexRequest = new IndexRequest(aliasName, typeName, String.valueOf(d.getId()));
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        bulkRequest.timeout(TimeValue.timeValueMinutes(40));
        try {
            BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (bulkResponse.hasFailures()) {
                log.error("商品数据批量添加失败！，失败信息：" + bulkResponse.buildFailureMessage() + ", status: "
                        + bulkResponse.status().getStatus());
            } else {
                for(EsGoodsDTO d : postList){
                    CommodityInfoDTO commodityInfoDTO = new CommodityInfoDTO();
                    commodityInfoDTO.setIsSynEs(1);
                    EntityWrapper wrapper = new EntityWrapper();
                    wrapper.eq("id",d.getId());
                    commodityInfoService.update(commodityInfoDTO,wrapper);
                }
                log.info("商品数据批量添加成功！");
            }
        } catch (Exception e) {
            log.info("商品批量添加失败");
            e.printStackTrace();
        }

    }

    @Async
    @Override
    public void deleteData(String aliasName, String typeName, String id) {
        try {
            elasticsearchService.deleteData(aliasName, typeName, id);
        } catch (Exception e) {
            log.error("ES根据ID删除商品错误信息:{}", e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public boolean checkIndex(String indexName) {
        try {
            GetIndexRequest request = new GetIndexRequest(indexName);
            boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
            if (exists) {
                return true;
            }
            // 如果不存在创建索引
            boolean index = elasticsearchService.createIndex(indexName, aliasename, 1, 1);
            if (!index) {
                return false;
            }
            // 索引创建成功后创建映射
            Class<?> clazz = EsGoodsDTO.class;
            boolean addMapping = elasticsearchService.addMapping(indexName, typeName, clazz);
            if (!addMapping) {
                return false;
            }
            // 映射创建成功后添加数据
            //this.add();
            return true;
        } catch (IOException e) {
            log.error("检查索引错误信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return false;
    }


    private Result addGoods() {
        Result<Object> result = new Result<>();
        List<CommodityEsVO> list = commodityInfoService.queryAllESGoods(0L);
        if (isNull(list)) {
            result.setCode(100003);
            result.setMsg("查询商品为空!");
            return result;
        }
        List<EsGoodsDTO> goodsList = new ArrayList<>();
        for (CommodityEsVO vo : list) {
            EsGoodsDTO goodsDTO = new EsGoodsDTO();
            goodsDTO.setId(vo.getId());
            goodsDTO.setLogUrl(vo.getLogUrl());
            goodsDTO.setGoodsName(vo.getGoodsName());
            goodsDTO.setGoodsNameIkSmart(vo.getGoodsName());
            goodsDTO.setGoodsNameIkMaxWord(vo.getGoodsName());
            goodsDTO.setDescription(vo.getDescription());
            goodsDTO.setPrice(vo.getPrice().doubleValue());
            goodsDTO.setOriginalPrice(vo.getOriginalPrice().doubleValue());
            goodsDTO.setPayUserNum(vo.getPayUserNum());
            goodsDTO.setSellerShopId(vo.getSellerShopId());
            goodsDTO.setSellerShopName(vo.getSellerShopName());
            goodsDTO.setSellerShopAddress(vo.getSellerShopAddress());
            goodsDTO.setBrandId(vo.getBrandId().toString());
            goodsDTO.setBrandName(vo.getBrandName());
            goodsDTO.setBrandNameIkSmart(vo.getBrandName());
            goodsDTO.setBrandNameIkMaxWord(vo.getBrandName());
            goodsDTO.setCategoryId(vo.getCategoryId());
            goodsDTO.setCategoryName(vo.getCategoryName());
            goodsDTO.setIsNew(vo.getIsNew());
            goodsDTO.setPopularity(vo.getPopularity());
            goodsDTO.setEvaluationNum(vo.getEvaluationNum());
            goodsDTO.setCreateTime(vo.getCreateTime());
            goodsDTO.setParentCategoryId(vo.getParentCategoryId());
            goodsDTO.setFirstCategoryId(vo.getFirstCategoryId());
            goodsDTO.setFilterIds(vo.getFilterIds());
            goodsDTO.setFilterNames(vo.getFilterNames());
            if (StringHelper.isNotEmpty(vo.getFilterNames())) {
                String[] split = vo.getFilterNames().split(",");
                goodsDTO.setFilterName(split);
            }
            if (StringHelper.isNotEmpty(vo.getLabelIds())) {
                String[] split = vo.getLabelIds().split(",");
                goodsDTO.setLabelIds(split);
            }
            goodsDTO.setIsXun(vo.getIsXun());
            goodsDTO.setBrowseAmount(vo.getBrowseAmount());
            goodsList.add(goodsDTO);
        }
        try {
            this.batchPost(goodsList.size(), 0, goodsList);
        } catch (IOException e) {
            log.info("添加商品到es失败!");
            e.printStackTrace();
        }
        result.setCode(0);
        result.setMsg("添加成功!");
        return result;
    }

    @Override
    public boolean checkIndexByIndexName(String indexName) {
        try {
            GetIndexRequest request = new GetIndexRequest(indexName);
            boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
            if (exists) {
                return true;
            }else{
                return false;
            }

        } catch (IOException e) {
            log.error("检查索引错误信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean addMappingAndAddDate(String indexName, Integer type) {
        try {
            Class<?> clazz;
            if (type.equals(1)) {
                clazz = EsGoodsDTO.class;
                boolean addMapping = elasticsearchService.addMapping(indexName, typeName, clazz);
                if (!addMapping) {
                    return false;
                }
                // 添加数据
                this.add();
            } else {
                clazz = EsShopDTO.class;
                boolean addMapping = elasticsearchService.addMapping(indexName, shopTypeName, clazz);
                if (!addMapping) {
                    return false;
                }
                // 添加数据
                shopSearchService.add();
            }
            return true;
        } catch (Exception e) {
            log.error("添加映射和添加数据错误信息:{}", e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 解析搜索字段
     *
     * @param searchFields
     * @return
     */
    private Map<String, Float> getFieldsMap(String searchFields) {
        String[] fieldsArray = searchFields.split(",");
        Map<String, Float> fields = Maps.newHashMap();
        for (String k : fieldsArray) {
            fields.put(k.split("\\^")[0], Float.parseFloat(k.split("\\^")[1]));
        }
        return fields;
    }

    /**
     * @Description: 批量发送数据
     * @Author: chenyu.wang
     * @Params: [size, begin, list]
     * @Date: 2020.11.18 09:40
     */
    private void batchPost(int size, int begin, List<EsGoodsDTO> list) throws IOException {
        if (size > batchImportSize) {
            addBatch(aliasename, typeName, begin, begin + batchImportSize, list);
            list = list.subList(begin + batchImportSize, list.size());
            batchPost(list.size(), 0, list);
        } else {
            addBatch(aliasename, typeName, begin, list.size(), list);
        }
    }

    /**
     * @Description: 批量添加信息
     * @Author: chenyu.wang
     * @Params: [aliasName, typeName, begin, end, totalList]
     * @Date: 2020.11.18 09:40
     */
    private boolean addBatch(String aliasName, String typeName, int begin, int end, List<EsGoodsDTO> totalList)
            throws IOException {
        List<EsGoodsDTO> postList = totalList.subList(begin, end);
        BulkRequest bulkRequest = new BulkRequest();
        for (EsGoodsDTO d : postList) {
            String jsonString = JSON.toJSONString(d);
            IndexRequest indexRequest = new IndexRequest(aliasName, typeName, String.valueOf(d.getId()));
            indexRequest.source(jsonString, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        bulkRequest.timeout(TimeValue.timeValueMinutes(40));
        BulkResponse bulkResponse = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        if (bulkResponse.hasFailures()) {
            log.error("数据批量添加失败！，失败信息：" + bulkResponse.buildFailureMessage() + ", status: "
                    + bulkResponse.status().getStatus());
        } else {
            log.info("数据批量添加成功！");
            return true;
        }
        return false;
    }

    /**
     * @Description: 处理搜索结果高亮字段
     * @Author: chenyu.wang
     * @Params: [goodsNameIkSmart, goodsNameIkMaxWord]
     * @Date: 2020.12.28 15:54
     */
    private String updateHighlightField(HighlightField goodsNameIkSmart, HighlightField goodsNameIkMaxWord) {
        StringBuilder goodsName = new StringBuilder();
        if (goodsNameIkSmart != null && goodsNameIkMaxWord == null) {
            Text[] texts = goodsNameIkSmart.getFragments();
            for (Text text : texts) {
                goodsName.append(text);
            }
            return goodsName.toString();
        }
        if (goodsNameIkSmart == null && goodsNameIkMaxWord != null) {
            Text[] texts = goodsNameIkMaxWord.getFragments();
            for (Text text : texts) {
                goodsName.append(text);
            }
            return goodsName.toString();
        }
        if (goodsNameIkSmart != null && goodsNameIkMaxWord != null) {
            Text[] ikMaxWordFragments = goodsNameIkMaxWord.getFragments();
            for (Text ikMaxWordFragment : ikMaxWordFragments) {
                goodsName.append(ikMaxWordFragment);
            }
            return goodsName.toString();
        }
        return goodsName.toString();
    }

}

